import { EnvConfig } from './env.d';

// 默认环境变量值
const defaultEnv: EnvConfig = {
  // 应用配置
  NODE_ENV: 'development',
  PORT: 3000,
  DEBUG: true,
  
  // CORS配置
  CORS_ORIGIN: '*',
  CORS_CREDENTIALS: false,
  
  // 数据库配置
  DB_HOST: 'localhost',
  DB_PORT: 3306,
  DB_USERNAME: 'root',
  DB_PASSWORD: 'password',
  DB_NAME: 'testdb',
  DB_DIALECT: 'mysql',
  DB_LOGGING: true,
  DB_TIMEZONE: '+08:00',
  
  // 数据库连接池配置
  DB_POOL_MAX: 5,
  DB_POOL_MIN: 0,
  DB_POOL_ACQUIRE: 30000,
  DB_POOL_IDLE: 10000,
  
  // 高级配置
  LOG_LEVEL: 'debug',
  API_RATE_LIMIT: 1000,
  SESSION_SECRET: 'default-secret-key',
  SSL_ENABLED: false,
  COMPRESSION_ENABLED: false
};

// 环境变量读取器类
export class EnvReader {
  private static instance: EnvReader;
  private envConfig: EnvConfig;

  private constructor() {
    this.envConfig = this.loadEnvConfig();
  }

  public static getInstance(): EnvReader {
    if (!EnvReader.instance) {
      EnvReader.instance = new EnvReader();
    }
    return EnvReader.instance;
  }

  // 获取环境变量值
  public get<K extends keyof EnvConfig>(key: K): EnvConfig[K] {
    return this.envConfig[key];
  }

  // 获取所有配置
  public getAll(): EnvConfig {
    return { ...this.envConfig };
  }

  // 检查是否为生产环境
  public isProduction(): boolean {
    return this.envConfig.NODE_ENV === 'production';
  }

  // 检查是否为开发环境
  public isDevelopment(): boolean {
    return this.envConfig.NODE_ENV === 'development';
  }

  // 检查是否为测试环境
  public isStaging(): boolean {
    return this.envConfig.NODE_ENV === 'staging';
  }

  // 加载环境变量配置
  private loadEnvConfig(): EnvConfig {
    return {
      // 应用配置
      NODE_ENV: this.getString('NODE_ENV', defaultEnv.NODE_ENV),
      PORT: this.getNumber('PORT', defaultEnv.PORT),
      DEBUG: this.getBoolean('DEBUG', defaultEnv.DEBUG),
      
      // CORS配置
      CORS_ORIGIN: this.getCorsOrigin(),
      CORS_CREDENTIALS: this.getBoolean('CORS_CREDENTIALS', defaultEnv.CORS_CREDENTIALS),
      
      // 数据库配置
      DB_HOST: this.getString('DB_HOST', defaultEnv.DB_HOST),
      DB_PORT: this.getNumber('DB_PORT', defaultEnv.DB_PORT),
      DB_USERNAME: this.getString('DB_USERNAME', defaultEnv.DB_USERNAME),
      DB_PASSWORD: this.getString('DB_PASSWORD', defaultEnv.DB_PASSWORD),
      DB_NAME: this.getString('DB_NAME', defaultEnv.DB_NAME),
      DB_DIALECT: this.getDatabaseDialect(),
      DB_LOGGING: this.getBoolean('DB_LOGGING', defaultEnv.DB_LOGGING),
      DB_TIMEZONE: this.getString('DB_TIMEZONE', defaultEnv.DB_TIMEZONE),
      
      // 数据库连接池配置
      DB_POOL_MAX: this.getNumber('DB_POOL_MAX', defaultEnv.DB_POOL_MAX),
      DB_POOL_MIN: this.getNumber('DB_POOL_MIN', defaultEnv.DB_POOL_MIN),
      DB_POOL_ACQUIRE: this.getNumber('DB_POOL_ACQUIRE', defaultEnv.DB_POOL_ACQUIRE),
      DB_POOL_IDLE: this.getNumber('DB_POOL_IDLE', defaultEnv.DB_POOL_IDLE),
      
      // 高级配置
      LOG_LEVEL: this.getString('LOG_LEVEL', defaultEnv.LOG_LEVEL),
      API_RATE_LIMIT: this.getNumber('API_RATE_LIMIT', defaultEnv.API_RATE_LIMIT),
      SESSION_SECRET: this.getString('SESSION_SECRET', defaultEnv.SESSION_SECRET),
      REDIS_URL: this.getOptionalString('REDIS_URL'),
      SSL_ENABLED: this.getBoolean('SSL_ENABLED', defaultEnv.SSL_ENABLED),
      COMPRESSION_ENABLED: this.getBoolean('COMPRESSION_ENABLED', defaultEnv.COMPRESSION_ENABLED)
    };
  }

  // 获取字符串类型环境变量
  private getString(key: string, defaultValue: string): string {
    return process.env[key] || defaultValue;
  }

  // 获取可选字符串类型环境变量
  private getOptionalString(key: string): string | undefined {
    return process.env[key];
  }

  // 获取数字类型环境变量
  private getNumber(key: string, defaultValue: number): number {
    const value = process.env[key];
    if (value === undefined) return defaultValue;
    const num = parseInt(value, 10);
    return isNaN(num) ? defaultValue : num;
  }

  // 获取布尔类型环境变量
  private getBoolean(key: string, defaultValue: boolean): boolean {
    const value = process.env[key];
    if (value === undefined) return defaultValue;
    return value.toLowerCase() === 'true';
  }

  // 获取CORS来源配置
  private getCorsOrigin(): string | string[] {
    const value = process.env.CORS_ORIGIN;
    if (!value) return defaultEnv.CORS_ORIGIN;
    if (value === '*') return '*';
    return value.split(',').map(origin => origin.trim());
  }

  // 获取数据库方言
  private getDatabaseDialect(): EnvConfig['DB_DIALECT'] {
    const value = process.env.DB_DIALECT;
    if (!value) return defaultEnv.DB_DIALECT;
    const validDialects: EnvConfig['DB_DIALECT'][] = ['mysql', 'postgres', 'sqlite', 'mariadb', 'mssql'];
    return validDialects.includes(value as any) ? value as EnvConfig['DB_DIALECT'] : defaultEnv.DB_DIALECT;
  }

  // 验证环境变量
  public validate(): { isValid: boolean; errors: string[] } {
    const errors: string[] = [];
    const config = this.envConfig;

    // 验证端口号
    if (config.PORT < 1 || config.PORT > 65535) {
      errors.push(`端口号必须在 1-65535 之间，当前值: ${config.PORT}`);
    }

    // 验证必需字段
    const requiredFields = ['DB_HOST', 'DB_USERNAME', 'DB_PASSWORD', 'DB_NAME'];
    for (const field of requiredFields) {
      if (!config[field as keyof EnvConfig]) {
        errors.push(`缺少必需的环境变量: ${field}`);
      }
    }

    // 验证数据库连接池配置
    if (config.DB_POOL_MAX < config.DB_POOL_MIN) {
      errors.push('数据库连接池最大连接数不能小于最小连接数');
    }

    // 验证API速率限制
    if (config.API_RATE_LIMIT < 1) {
      errors.push('API速率限制必须大于0');
    }

    // 生产环境特殊验证
    if (config.NODE_ENV === 'production') {
      if (config.DEBUG) {
        errors.push('生产环境不应启用调试模式');
      }
      if (config.SESSION_SECRET === 'default-secret-key') {
        errors.push('生产环境必须设置自定义的SESSION_SECRET');
      }
      if (config.CORS_ORIGIN === '*') {
        errors.push('生产环境不应允许所有CORS来源');
      }
    }

    return {
      isValid: errors.length === 0,
      errors
    };
  }

  // 打印环境变量信息（仅开发环境）
  public printEnvInfo(): void {
    if (this.isDevelopment()) {
      console.log('=== 环境变量配置 ===');
      console.log(`环境: ${this.envConfig.NODE_ENV}`);
      console.log(`端口: ${this.envConfig.PORT}`);
      console.log(`调试模式: ${this.envConfig.DEBUG}`);
      console.log(`日志级别: ${this.envConfig.LOG_LEVEL}`);
      console.log(`API速率限制: ${this.envConfig.API_RATE_LIMIT}`);
      console.log(`数据库: ${this.envConfig.DB_HOST}:${this.envConfig.DB_PORT}/${this.envConfig.DB_NAME}`);
      console.log(`数据库方言: ${this.envConfig.DB_DIALECT}`);
      console.log(`连接池: ${this.envConfig.DB_POOL_MAX} 最大连接`);
      console.log(`SSL启用: ${this.envConfig.SSL_ENABLED}`);
      console.log(`压缩启用: ${this.envConfig.COMPRESSION_ENABLED}`);
    }
  }
}

// 导出单例实例
export const envReader = EnvReader.getInstance();

// 便捷函数
export const getEnv = <K extends keyof EnvConfig>(key: K): EnvConfig[K] => envReader.get(key);
export const getAllEnv = (): EnvConfig => envReader.getAll();
export const isProduction = (): boolean => envReader.isProduction();
export const isDevelopment = (): boolean => envReader.isDevelopment();
export const isStaging = (): boolean => envReader.isStaging();
export const validateEnv = () => envReader.validate();
export const printEnvInfo = () => envReader.printEnvInfo(); 